﻿using UnityEngine;

// 实体单例

namespace Tools.Singleton
{
    public class UnitySingleton<T> : MonoBehaviour where T : Component
    {
        private static T _instance = null;

        public static T Instance
        {
            get 
            {
                if (_instance == null)
                {
                    _instance = FindObjectOfType<T>() as T;
                    if (_instance == null)
                    {
                        GameObject go = new GameObject();
                        _instance = (T)go.AddComponent<T>();
                        go.hideFlags = HideFlags.DontSave;
                        go.name = typeof(T).Name;
                    }
                }
                return _instance;
            }
        }

        private void Awake()
        {
            DontDestroyOnLoad(this.gameObject);

            if (_instance == null)
            {
                _instance = this as T;
            }
            else
            {
                GameObject.DestroyImmediate(this.gameObject);
            }
        }
    }
}
// 举个栗子
namespace Tools.Singleton.Test
{
    public class ClassName : UnitySingleton<ClassName>
    {
        // 。。。。。。
    }
}